﻿using DemoServiceLibrary;
using System;
using System.Diagnostics;

namespace DemoServer
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
    public class ServerInfoProvider : IServerInfoProvider
    {
        private PerformanceCounter processorTimeCounter;
        private PerformanceCounter ramCounter;
        private static string serverName = Environment.MachineName;

        public ServerInfoProvider()
        {
            this.processorTimeCounter = new PerformanceCounter();
            this.processorTimeCounter.CategoryName = "Processor Information";
            this.processorTimeCounter.CounterName = "% Processor Time";
            this.processorTimeCounter.InstanceName = "_Total";

            this.ramCounter = new PerformanceCounter();
            this.ramCounter.CategoryName = "Memory";
            this.ramCounter.CounterName = "Available MBytes";
        }

        public ServerInfo GetServerInfo()
        {
            float processorTime = this.processorTimeCounter.NextValue() / 100;
            float availableMemory = this.ramCounter.NextValue() / 1000;

            return new ServerInfo
            {
                ServerName = serverName,
                ProcessorTime = processorTime.ToString("P"),
                AvailableMemory = availableMemory.ToString("N")
            };
        }
    }
}
